<!doctype html>
<!--
Copyright 2014 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="description" content="Sample of using a service worker to provide a fallback response when a fetch() fails.">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Service Worker Sample: Mock Responses</title>

    <!-- Add to homescreen for Chrome on Android -->
    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="../../images/touch/chrome-touch-icon-192x192.png">

    <!-- Add to homescreen for Safari on iOS -->
    <meta name="apple-mobile-web-app-title" content="Service Worker Sample: Mock Responses">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" href="../../images/apple-touch-icon-precomposed.png">

    <!-- Tile icon for Win8 (144x144 + tile color) -->
    <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <link rel="icon" href="../../images/favicon.ico">

    <script>
      // Service workers require HTTPS (http://goo.gl/lq4gCo). If we're running on a real web server
      // (as opposed to localhost on a custom port, which is whitelisted), then change the protocol to HTTPS.
      if ((!location.port || location.port == "80") && location.protocol != 'https:') {
        location.protocol = 'https:';
      }
    </script>

    <link rel="stylesheet" href="../../styles/main.css">
  </head>

  <body>
    <h1>Service Worker Sample: Mock Responses</h1>

    <p>Available in <a href="https://www.chromestatus.com/feature/6561526227927040">Chrome 40+</a></p>

    <p>
      This sample demonstrates basic service worker registration, with the service worker's fetch handler
      not taking any special action for most requests. However, there is special behavior if a request
      is made to the <a href="https://developers.google.com/url-shortener/">Google URL Shortener API</a>
      and a custom request header is set, <code>X-Mock-Response</code>. (There's no special significance
      to this name; any convention that both the controlled page and the service worker agree on could be used.)
      Instead of returning actual responses for those API requests, the service worker will return mock response
      that should appear identical to a real API response from the perspective of this controlled page.
    </p>

    <p>
      Visit <code>chrome://inspect/#service-workers</code> and click on the "inspect" link below
      the registered service worker to view logging statements for the various actions the
      <code><a href="service-worker.js">service-worker.js</a></code> script is performing.
    </p>

    <div class="output">
      <p id="status"></p>

      <div id="request" style="display: none">
        <p>
          Try this example both with the box checked (which will return a static, mock response) and
          with the box unchecked (which will make an actual call to the URL Shortener API). The response
          will be handled identically by this page regardless of whether it is mocked or genuine.
        </p>

        <div>
          <input id="original-url" value="https://www.google.com/" size="50">
          <button id="shorten-button">Shorten</button>
        </div>
        <div>
          <input id="mock-checkbox" type="checkbox" checked>Mock Response</input>
        </div>

        <p>Short URL: <a id="short-url"></a></p>
      </div>
    </div>

    <script>
      function showRequest() {
        document.querySelector('#shorten-button').addEventListener('click', makeApiRequest);
        document.querySelector('#request').style.display = 'block';
      }

      function makeApiRequest() {
        var xhr = new XMLHttpRequest();
        // See https://developers.google.com/url-shortener/v1/getting_started#shorten
        xhr.open('POST', 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyCr0XVB-Hz1ohPpjvLatdj4qZ5zcSohHsU');
        xhr.setRequestHeader('Content-Type', 'application/json');
        // Only set the custom 'X-Mock-Response' header if the box is checked. The service worker will
        // use the header's presence to determine whether to return a mock or genuine response.
        if (document.querySelector('#mock-checkbox').checked) {
          xhr.setRequestHeader('X-Mock-Response', 'yes');
        }

        xhr.addEventListener('load', function() {
          var response = JSON.parse(xhr.response);
          console.log('Response is', response);

          var shortUrlElement = document.querySelector('#short-url');
          shortUrlElement.href = response.id;
          shortUrlElement.textContent = response.id;
        });

        var request = {
          longUrl: document.querySelector('#original-url').value
        };
        var requestJson = JSON.stringify(request);
        xhr.send(requestJson);
      }

      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function() {
          if (navigator.serviceWorker.controller) {
            // If .controller is set, then this page is being actively controlled by the service worker.
            document.querySelector('#status').textContent = 'The service worker is currently handling network operations.';

            showRequest();
          } else {
            // If .controller isn't set, then prompt the user to reload the page so that the service worker can take
            // control. Until that happens, the service worker's fetch handler won't be used.
            document.querySelector('#status').textContent = 'Please reload this page to allow the service worker to handle network operations.';
          }
        }).catch(function(error) {
          // Something went wrong during registration. The service-worker.js file
          // might be unavailable or contain a syntax error.
          document.querySelector('#status').textContent = error;
        });
      } else {
        // The current browser doesn't support service workers.
        var aElement = document.createElement('a');
        aElement.href = 'http://www.chromium.org/blink/serviceworker/service-worker-faq';
        aElement.textContent = 'unavailable';
        document.querySelector('#status').appendChild(aElement);
      }
    </script>

    <script>
      /* jshint ignore:start */
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-53563471-1', 'auto');
      ga('send', 'pageview');
      /* jshint ignore:end */
    </script>
    <!-- Built with love using Web Starter Kit -->
  </body>
</html>
